package com.starleague.battletech.controller.jpa.appengine;

import java.io.IOException;

import com.starleague.battletech.command.AbstractBattletechCommand;
import com.starleague.battletech.controller.IBattletechContext;
import com.starleague.battletech.game.dto.IBattletechGameDto;
import com.starleague.battletech.game.dto.IBattletechTeamDto;
import com.starleague.battletech.game.jpa.appengine.BattletechGameGae;
import com.starleague.battletech.game.jpa.appengine.BattletechTeamGae;
import com.starleague.battletech.unit.mech.dto.IMechDto;
import com.starleague.battletech.unit.mech.jpa.appengine.MechGae;
import com.starleague.jpa.appengine.GaeTransaction;

public class BattletechContextGae
        implements IBattletechContext
{
    private final GaeTransaction transaction;
    private final IBattletechGameDto gameDto;

    public BattletechContextGae(GaeTransaction transaction,
                                IBattletechGameDto gameDto)

    {
        this.gameDto = gameDto;
        this.transaction = transaction;
    }

    @Override
    public void close() throws IOException
    {
        this.transaction.close();
    }

    @Override
    public void onSuccess(AbstractBattletechCommand command)
    {
        this.transaction.commit();
    }

    @Override
    public void onFailure(AbstractBattletechCommand command,
                          String reason)
    {
        this.transaction.rollback();
    }

    @Override
    public BattletechGameGae resolveGame()
    {
        return this.transaction.findByUid(BattletechGameGae.class, this.gameDto.getUid());
    }

    @Override
    public BattletechTeamGae resolveTeam(IBattletechTeamDto teamDto)
    {
        return this.transaction.findByUid(BattletechTeamGae.class, teamDto.getUid());
    }

    @Override
    public MechGae resolveMech(IMechDto mechDto)
    {
        return this.transaction.findByUid(MechGae.class, mechDto.getUid());
    }
}
